# -*- coding: utf-8 -*- 
from main import MainHandler
from google.appengine.api import users
from src.model import UserPrefs, Blockerator
import logging

class NameChooseHandler(MainHandler):
	RUS = u'абвгдеёжзийклмнопрстуфхцчшщьъыэюя'
	ENG = 'abcdefghijklmnopqrstuvwxyz'

	def hasChar(self, name, array):
		for letter in name:
			if letter in array:
				return True
		return False

	def post(self):
		name = self.request.get('name')
		change = self.request.get('change')
		logging.info('name=' + name)
		current_user = users.get_current_user()
		if (name != '' and name) and not current_user is None:
			if change != '' or self.current_user() is None:
				if self.hasChar(name, NameChooseHandler.ENG) and self.hasChar(name, NameChooseHandler.RUS):
					self.render_template('nickname.html', {
						'change': change,
						'error': 'Пожалуйста, не используйте одновременно русские и английские символы в имени'
					})
					return
					
				if UserPrefs.person_by_name(name):
					self.render_template('nickname.html', {
						'change': change,
						'error': 'Извините, но такое имя уже занято.'
					})
					return
				else:
					userprefs = self.current_user()
					logging.info(userprefs)
					logging.info(current_user)
					if userprefs is None:
						userprefs = UserPrefs()
						muter = Blockerator()
						muter.put()
						userprefs.muter = muter
					userprefs.set_user_name(name)
					userprefs.user = current_user
					userprefs.put()
		self.redirect('/')
